package cn.wuxing.mediation.web.controller.zzd;

import cn.hutool.core.lang.generator.SnowflakeGenerator;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import cn.wuxing.mediation.common.core.controller.BaseController;
import cn.wuxing.mediation.common.core.domain.AjaxResult;
import cn.wuxing.mediation.common.core.domain.entity.SysUser;
import cn.wuxing.mediation.common.utils.SecurityUtils;
import cn.wuxing.mediation.system.domain.MessageNotifications;
import cn.wuxing.mediation.system.domain.StgDscHuzBiz018VisitPetitionDfWxq;
import cn.wuxing.mediation.system.mapper.StgDscHuzBiz018VisitPetitionDfWxqMapper;
import cn.wuxing.mediation.system.service.ISysUserService;
import cn.wuxing.mediation.web.controller.util.OrganizationEmployeeFetcher;
import com.alibaba.xxpt.gateway.shared.api.request.*;
import com.alibaba.xxpt.gateway.shared.api.response.*;
import com.alibaba.xxpt.gateway.shared.client.http.ExecutableClient;
import com.alibaba.xxpt.gateway.shared.client.http.IntelligentGetClient;
import com.alibaba.xxpt.gateway.shared.client.http.PostClient;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.List;
import java.util.UUID;

import static cn.wuxing.mediation.web.controller.util.OrganizationEmployeeFetcher.ORG_DETAILS_URL;

@Slf4j
@RestController()
@RequestMapping("/zzd")
public class ZzdDeptController extends BaseController {

    @Value("${dingIf.APP_KEY}")
    private String APP_KEY;

    @Value("${dingIf.APP_SECRET}")
    private String APP_SECRET;

    @Value("${dingIf.TENANT_ID}")
    private String TENANT_ID;

    @Value("${dingIf.DOMAIN_NAME}")
    private String DOMAIN_NAME;

    @Value("${dingQr.PROTOCAL}")
    private String PROTOCAL;//协议

    @Value("${zzd.password}")
    private String password;//密码

    @Resource
    private OrganizationEmployeeFetcher organizationEmployeeFetcher;

    @Autowired
    private ISysUserService userService;

    //单例
    private ExecutableClient singletonExecutableClient = null;

    /**
     * 获取用户列表
     */
//    @GetMapping("/updatePwd")
    public void UserList(SysUser user)
    {
        List<SysUser> list = userService.selectUserListTwo(user);
        log.info("=================================开始修改密码=====================");
        for (SysUser sysUser :list){
            sysUser.setPassword(SecurityUtils.encryptPassword(password));
            int i = userService.resetPwd(sysUser);
            String s="";
            if(i>0){
                s="成功";
            }else {
                s="失败";
            }
            log.info(sysUser.getUserName()+"修改密码:"+s);
        }
        log.info("=================================修改密码结束=====================");
    }


    private ExecutableClient getExecutableClient() {
        if (singletonExecutableClient == null) {
            singletonExecutableClient = ExecutableClient.getInstance();
            singletonExecutableClient.setAccessKey(APP_KEY);
            singletonExecutableClient.setSecretKey(APP_SECRET);
            singletonExecutableClient.setDomainName(DOMAIN_NAME);
            singletonExecutableClient.setProtocal(PROTOCAL);
            singletonExecutableClient.setTimeout(300 * 1000);
            singletonExecutableClient.init();
            return singletonExecutableClient;
        }
        return singletonExecutableClient;
    }

//    @GetMapping("/dept")
    public void getDept() {

        ExecutableClient executableClient = getExecutableClient();

        //executableClient保证单例
        IntelligentGetClient intelligentGetClient = executableClient.newIntelligentGetClient("/auth/scopesV2");
        OapiAuthScopesV2Request oapiAuthScopesV2Request = new OapiAuthScopesV2Request();
        //租户ID
        oapiAuthScopesV2Request.setTenantId(Long.valueOf(TENANT_ID));
        //获取结果
        OapiAuthScopesV2Response apiResult = intelligentGetClient.get(oapiAuthScopesV2Request);

        logger.info("==============吴兴区：{}", JSONUtil.toJsonStr(apiResult));
        String data = apiResult.getContent();
        List<String> deptVisibleScopes = JSONUtil.parseObj(data).getBeanList("deptVisibleScopes", String.class);


        organizationEmployeeFetcher.initOrganizationalStructure(deptVisibleScopes.get(0));

    }

    //    @GetMapping("/deptDetail")
    public String getDeptDetail() {
        ExecutableClient executableClient = getExecutableClient();
        PostClient postClient = executableClient.newPostClient(ORG_DETAILS_URL);
        postClient.addParameter("tenantId", TENANT_ID);
        postClient.addParameter("organizationCodes", "GO_33fae8273a344e508ebf272a58987c53");
        logger.info("吴兴区=======================批量获取组织详情参数是:{}", "GO_33fae8273a344e508ebf272a58987c53");
        String apiResult = postClient.post();
        logger.info("吴兴区=======================批量获取组织详情结果是:{}", apiResult);

        return apiResult;
    }

    //分页获取下⼀级组织
//    @GetMapping("/code")
    public AjaxResult getDeptPage() {
        ExecutableClient executableClient = getExecutableClient();

        ///mozi/fusion/getOrganizationTypes
        ///mozi/organization/getRootOrganization
        IntelligentGetClient intelligentGetClient = executableClient
                .newIntelligentGetClient("/mozi/fusion/getOrganizationTypes");
        OapiMoziFusionGetOrganizationTypesRequest oapiMoziFusionGetOrganizationTypesRequest = new
                OapiMoziFusionGetOrganizationTypesRequest();

        oapiMoziFusionGetOrganizationTypesRequest.setTenantId(Long.getLong(TENANT_ID));

        OapiMoziFusionGetOrganizationTypesResponse apiResult = intelligentGetClient
                .get(oapiMoziFusionGetOrganizationTypesRequest);

        System.out.println(apiResult);

        return null;
    }


    //消息通知
//    @GetMapping("/message")
    public AjaxResult message() {
        IntelligentGetClient intelligentGetClient = getExecutableClient()
                .newIntelligentGetClient("/message/workNotification");
        OapiMessageWorkNotificationRequest oapiMessageWorkNotificationRequest = new OapiMessageWorkNotificationRequest();
        //接收者的部门id列表
        oapiMessageWorkNotificationRequest.setOrganizationCodes("字符串");
        //接收人用户ID
        oapiMessageWorkNotificationRequest.setReceiverIds("字符串");
        //租户ID
        oapiMessageWorkNotificationRequest.setTenantId(TENANT_ID);
        //业务消息id
        oapiMessageWorkNotificationRequest.setBizMsgId("字符串");
        //消息对象
        oapiMessageWorkNotificationRequest.setMsg("字符串");
        //获取结果
        OapiMessageWorkNotificationResponse apiResult = intelligentGetClient.get(oapiMessageWorkNotificationRequest);

        System.out.println(apiResult);

        return null;
    }


//    @GetMapping("/employee")
    public void id() {
        ExecutableClient executableClient = getExecutableClient();
        IntelligentGetClient intelligentGetClient = executableClient.newIntelligentGetClient("/mozi/employee/get_by_mobile");
        OapiMoziEmployeeGetByMobileRequest oapiMoziEmployeeGetByMobileRequest = new OapiMoziEmployeeGetByMobileRequest();
        //手机区号
        oapiMoziEmployeeGetByMobileRequest.setAreaCode("86");
        //租户ID
        oapiMoziEmployeeGetByMobileRequest.setTenantId(Long.valueOf(TENANT_ID));
        //账号类型
        oapiMoziEmployeeGetByMobileRequest.setNamespace("local");
        //手机号
        oapiMoziEmployeeGetByMobileRequest.setMobile("18654103591");
        //获取结果
        OapiMoziEmployeeGetByMobileResponse apiResult = intelligentGetClient.get(oapiMoziEmployeeGetByMobileRequest);
        logger.info("=======================用户信息:{}", JSONUtil.toJsonStr(apiResult));

        String data1 = apiResult.getContent().getData();
        log.info("==================发送消息的accountId:{}", JSONUtil.parseObj(data1).get("accountId").toString());
        MessageNotifications messageNotifications = new MessageNotifications();
        messageNotifications.setEventCode("JF2024-12-06");
        messageNotifications.setAccountId(JSONUtil.parseObj(data1).get("accountId").toString());
        messageNotifications.setId(new SnowflakeGenerator().next());
        organizationEmployeeFetcher.
                sendMessage(messageNotifications);
    }
}
